﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CrawlerWeb.Models;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace CrawlerWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Run()
        {
            //获取运行目录路径
            var directory = System.IO.Directory.GetCurrentDirectory();
            //得到chromedriver.exe目录路径
            string path = directory + "/wwwroot/tool";

            var option = new ChromeOptions();
            //是否隐藏浏览器，如果注释掉的话，那么会在启动的时候打开谷歌浏览器，在页面上可以看到填单的操作，如果取消的话，就只有cmd窗口，谷歌浏览器隐匿运行        
            option.AddArgument("headless");
            option.AddArgument("window-size=1920,1080");

            //设置cmd窗口不弹出来
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(path);
            service.HideCommandPromptWindow = true;

            //初始化IWebDriver对象
            IWebDriver driver = new ChromeDriver(service, option);
            //访问url页面
            driver.Navigate().GoToUrl("https://www.baidu.com");

            driver.FindElement(By.Name("tj_trmap")).Click();//定位地图并点击
            driver.FindElement(By.XPath("//input[@id='sole-input']")).SendKeys("广东省深圳市"); //输入值
            driver.FindElement(By.Id("search-button")).Click(); //点击查询

            //获取页面源码
            //Console.WriteLine(driver.PageSource);

            //关掉driver
            //driver.Quit();
            ViewBag.data = driver.PageSource;

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
